let product
//全局商品,通过接口获取,用于添加购物

/* 
 * 获取商品ID
 */
function getProductId() {
    let url = location.href
    // console.log(location.search)
    url = url.substring(url.indexOf('?') + 1)
    let arr = url.split('=')
    let id = arr[1]
    return id
}


/*
 * 根据ID查询商品详情接口
 */
function loadProuctDetail() {
    let id = getProductId()
    axios({
        method: 'get',
        url: 'http://api.yuguoxy.com/api/shop/find',
        params: {
            id,
        },
    }).then(response => {
        let data = response.data
        let {
            resultCode,
            resultInfo
        } = data
        if (resultCode == 1) {

            product = resultInfo //商品详情对象
            showProductDetail(product)

            // onGoToDetails(product)
        }
    })
}

/* 
 * 动态渲染
 */
function showProductDetail(product) {
    // console.log(product);
    let liStr = product.list
        .map(item => {
            return `<li><img src="${item}" alt=""></li>`
        })
        .join('')

    let detailStr =
        `<div class="detail-l">
                        <div class="show-box" >
                            <img src="${product.picture}" alt="">
                            <div class="mask"></div>
                        </div>
                        <ul>` +
        liStr +
        `</ul>
                    </div>

                    <div class="detail-r">
                        <div class="box"><img src="${product.picture}" alt="" class="img1"></div>
                        
                        <div class="detail-g">
                            <h2>${product.product}</h2>
                            <img src="../static/images/details-img1.png" alt="">
                            <div class="detail-menu">              
                                <span class="sp1">61狂欢</span>
                                <span class="sp2">￥</span>
                                <span class="sp3">${product.price}</span>
                                <span class="sp4">狂欢价</span>
                               
                            </div>
                            <button class="buy-now">立即购买</button>
                            <button class="add-cart" onclick="onAddCart()">加入购物车</button>
                            <button class="look-cart" onclick="onLookCart()">查看购物车</button>
                        </div>
                    </div>`

    const detailWrapper = document.querySelector('#detail')
    // console.log(detailWrapper);
    detailWrapper.innerHTML = detailStr
    let magnifier = new Glass('#detail')
    magnifier.init()
    magnifier.onGlass()
    magnifier.onShowHide()
    magnifier.onTab()
    magnifier.onDetail()

}


/* 
 * 添加商品:
    1.保存商品到localStorage
    2.添加相同商品,改变数量
        添加之前,根据ID判断商品数组中是否已经存在,如果存在则数量加一,否则添加新的商品

 */
function onAddCart() {
    // 1. 获取商品 product
    // 2. 获取购物车localStorage中原来商品数组,如果是第一次添加商品， 商品数组为[]
    let cartListStr = localStorage.getItem('DS-CART-LIST')
    let cartList = JSON.parse(cartListStr) || []

    //添加相同商品，改变数量
    //添加之前，根据id判断商品数组中是否已经存在，如果存在数量加一，否则添加新商品
    let oldProduct = cartList.find(item => item.id == product.id)
    if (oldProduct) {
        oldProduct.num++ //添加相同商品，改变数量
    } else {
        // 3.1 构造添加到购物车的商品
        let cartProdcut = {
            id: product.id, //商品id
            name: product.product, //商品名称
            price: product.price, //价格
            url: product.picture, //图片
            num: 1, //数量
            state: false, //状态
        }
        cartList.push(cartProdcut)
    }

    // 4. 持久化存储到购物车localStorage
    localStorage.setItem('DS-CART-LIST', JSON.stringify(cartList))
}


// 商品放大镜
// 遮罩层随光标移动而移动，右边大图反方向运行
//          1. 遮罩层随光标移动而移动
//             绑定光标在显示盒子中的移动事件mousemove
//             获取光标相对自身的位置复制给遮罩层

//          2. 右边大图反方向运行
// 			计算比例
// 				图片比例
// 				移动距离比例


class Glass {
    constructor(id) {
        this.rootEle = document.querySelector(id)
        // console.log(id);
        // console.log(this.rootEle);
        this.showBox = this.rootEle.querySelector('.show-box') //显示盒子
        // console.log(this.showBox);
        this.mask = this.rootEle.querySelector('.show-box>.mask') //遮罩层
        this.glassBox = this.rootEle.querySelector('.box') //放大镜区域
        this.bigPic = this.rootEle.querySelector('.img1') //背景图片
        this.uls = this.rootEle.querySelectorAll('.detail-l li') //所有选项卡
        this.showImg = this.rootEle.querySelector('.show-box>img')
        // console.log(this.showImg);
    }


    /**
     * 初始化比例
     * 背景图 = 放大镜*显示盒子/遮罩层
     *
     */
    init() {
        console.log(this.glassBox.clientWidth);
        let w = (this.glassBox.clientWidth * this.showBox.clientWidth) / this.mask.clientWidth
        let h = (this.glassBox.clientHeight * this.showBox.clientHeight) / this.mask.clientHeight
        this.bigPic.style.width = w + 'px'
        this.bigPic.style.height = h + 'px'
    }
    onGlass() {
        let that = this
        // console.log(this);
        //1. 绑定光标在显示盒子中的移动事件mousemove
        this.showBox.addEventListener('mousemove', function (e) {
            // console.log(1);
            e = e || window.event
            let x = e.offsetX - that.mask.clientWidth / 2
            let y = e.offsetY - that.mask.clientHeight / 2

            //边界检查
            if (x < 0) {
                x = 0
            }
            if (x > that.showBox.clientWidth - that.mask.clientWidth) {
                x = that.showBox.clientWidth - that.mask.clientWidth
            }
            if (y < 0) {
                y = 0
            }
            if (y > that.showBox.clientHeight - that.mask.clientHeight) {
                y = that.showBox.clientHeight - that.mask.clientHeight
            }

            that.mask.style.left = x + 'px'
            that.mask.style.top = y + 'px'


            //右边大图反方向运行
            /**
             * 计算移动比例
             *  背景图移距离X = 遮罩层移动距离x * 放大镜w/遮罩层w
             *  背景图移距离y = 遮罩层移动距离y * 放大镜h/遮罩层h
             *
             */

            let moveX = (x * that.glassBox.clientWidth) / that.mask.clientWidth
            let moveY = (y * that.glassBox.clientHeight) / that.mask.clientHeight

            that.bigPic.style.left = `${-moveX}px`
            that.bigPic.style.top = `${-moveY}px`
        })
    }
    /**
     * 移入显示遮罩层
     * 移出隐藏遮罩层
     */
    onShowHide() {
        this.showBox.addEventListener('mouseover', () => {
            this.mask.style.display = 'block' //显示
            this.bigPic.style.display = 'block' //显示
            this.init()
        })

        this.showBox.addEventListener('mouseout', () => {
            this.mask.style.display = 'none' //隐藏
            this.bigPic.style.display = 'none' //隐藏
        })

    }

    /**
     * 选项切换
     * 点击选项小图时，显示盒子图片和背景图片切换为相应图片
     *   1. 获取所有选项，绑定点击事件
     *   2.显示盒子图片和背景图片切换为相应图片
     */
    onTab() {
        let that = this // 保存当前glass放大镜对象到that变量中
        for (let i = 0; i < this.uls.length; i++) {
            this.uls[i].addEventListener('click', function () {
                //清除原来选中效果
                that.onClear()
                //设置当前选项效果
                this.classList.add('active')

                //显示盒子图片和背景图片切换为相应图片
                that.showImg.src = this.firstElementChild.src
                that.bigPic.src = this.firstElementChild.src
            })
        }
    }

    /*
     * 清除所有选项选中效果
     */
    onClear() {
        for (let i = 0; i < this.uls.length; i++) {
            this.uls[i].classList.remove('active')
        }
    }


    //通向购物车的天梯
    onDetail() {
        let goToCart = document.querySelector('.look-cart')
        let addCart = document.querySelector('.add-cart')
        goToCart.addEventListener('click', () => {
            location.href = '../pages/cart.html'
        })
        addCart.addEventListener('click', () => {
            alert('宝,您的商品已添加至购物车,快快去查看叭~')
        })
        
    }

}










/*
 * 查看
 *  2. 跳转到购物车列表界面
 */


loadProuctDetail()